import 'dart:convert';
import 'dart:developer';
import 'dart:ffi';
import 'package:get/get_connect.dart';
import 'package:get/instance_manager.dart';
import 'package:http/http.dart' as http;
import 'package:m6/Public/manager/app_manager.dart';
import 'package:m6/Untils/aes.dart';
import 'package:m6/Untils/api.dart';

enum RequestMethod { post, get }

class CustomerResponse {
  int code = -1;
  String msg = 'error execption';
  Map<String, dynamic>? data;

  Map<String, dynamic> toJson() =>
      <String, dynamic>{'code': code, 'msg': msg, "data": data};
}

class Request {
  static Future<CustomerResponse> post(
      String url, Map<String, dynamic>? params) async {
    final realParams = handleParams(params);
    final uri = Uri.http(Domain.replaceAll("http://", ""), handleUrl(url));
    return startRequest(uri, RequestMethod.post, realParams);
  }

  static Future<CustomerResponse> get(
      String url, Map<String, dynamic>? params) async {
    final realParams = handleParams(params);
    final uri =
        Uri.http(Domain.replaceAll("http://", ""), handleUrl(url), realParams);
    return startRequest(uri, RequestMethod.get, null);
  }

  static Future<CustomerResponse> startRequest(
      Uri uri, RequestMethod method, Map<String, dynamic>? params) async {
    http.Response? response;
    try {
      if (method == RequestMethod.post) {
        response =
            await http.post(uri, headers: defaultHeaders(), body: params);
      } else if (method == RequestMethod.get) {
        response = await http.get(uri, headers: defaultHeaders());
      }
    } catch (e) {
      print(">>>>>>>>>>>$e");
    }

    CustomerResponse cusResponse = handleResponse(response);
    requestLog(response, cusResponse.toJson());
    return cusResponse;
  }

  static CustomerResponse handleResponse(http.Response? response) {
    CustomerResponse cusResponse = CustomerResponse();
    if (response != null) {
      cusResponse.code = response.statusCode;
      final str = utf8.decode(response.bodyBytes);
      var res = {};
      try {
        res = jsonDecode(str);
      } catch (error) {}
      if (res.isEmpty) {
        final aesDecString = aesDecode(str);
        Map? decMap;
        try {
          decMap = jsonDecode(aesDecString) as Map;
        } catch (error) {}
        if (decMap != null) {
          final code = decMap["code"] as int;
          cusResponse.code = code;
          cusResponse.msg = decMap["message"];
          cusResponse.data = decMap["data"];
        }
      } else {
        cusResponse.code = res["status"];
        cusResponse.msg = res["message"];
        cusResponse.data = res as Map<String, dynamic>;
      }
    }
    return cusResponse;
  }

  static Map<String, dynamic> defaultParams() {
    final AppManager appManager = Get.find();
    return {
      "itemCode": AppProductCode,
      "languageCode": "ESP",
      "sessionId": appManager.session,
      "isIOS": "1"
    };
  }

  static Map<String, String> defaultHeaders() {
    return {"content-type": "application/x-www-form-urlencoded"};
  }

  //处理URL
  static String handleUrl(String urlStr) {
    final arr = urlStr.split("/");
    final url = "/${arr[1]}/Mp/abc${arr.last}xyz";
    return url;
  }

  static Map<String, dynamic> handleParams(Map<String, dynamic>? params) {
    Map<String, dynamic> a = {};
    if (params != null) {
      a.addEntries(params.entries);
    }
    a.addEntries(defaultParams().entries);
    Map<String, dynamic> b = {};
    for (var key in a.keys) {
      var value = a[key];
      if (value == null) {
        continue;
      }
      final newKey = "abc${key}xy";
      b[newKey] = value;
    }
    return b;
  }

  static requestLog(http.Response? resResponse, Map? responseData) {
    final request = resResponse?.request as http.Request?;
    Map? header = request?.headers;
    Uri? uri = request?.url;
    Map? queryParameters = uri?.queryParameters;
    String? params = request?.body;
    log("\n+++++++++++++++++++++++++++++++++++++++++++\n-> url:${request?.url}\n-> header:${header}\n-> queryParameters:${queryParameters}\n-> params:${params}\n-> response:${responseData}\n+++++++++++++++++++++++++++++++++++++++++++\n");
  }
}
